/**
 * 版权所有 2009-2012山东新北洋信息技术股份有限公司
 * 保留所有权利。
 */
package com.linyaonan.leetcode.easy._169;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName: leetcode
 * @Package: com.linyaonan.leetcode.easy._169
 * @ClassName: MajorityElement
 * @Author: linyaonan
 * @Date: 2019/11/13 17:18
 */
public class MajorityElement {

    public int majorityElement(int[] nums) {
        if (nums.length == 1) {
            return nums[0];
        }
        Map<Integer, Integer> save = new HashMap<>();
        save.put(nums[0], 1);
        for (int i = 1; i < nums.length; i++) {
            int key = nums[i];
            if (save.containsKey(key)) {
                if (save.get(key) + 1 > nums.length / 2) {
                    return key;
                } else {
                    save.put(key, save.get(key) + 1);
                }
            } else {
                save.put(key, 1);
            }
        }
        return 0;
    }

    public int majorityElement2(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length / 2];
    }
}
